package com.wanho.activemq.prototype.queue;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * 队列模式 同步消费者
 */
public class QueueSyncConsumer {
    public static void main(String[] args) {
        //创建一连接工厂
        ConnectionFactory connectionFactory  = new ActiveMQConnectionFactory("tcp://127.0.0.1:61616");
        try {
            //创建一个连接
            Connection connection = connectionFactory.createConnection();
            //打开连接
            connection.start();
            //创建一个回话
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            //创建一个目的地Destination
            Queue queue = session.createQueue("mytestqueue");
            //创建一个消费者
            MessageConsumer consumer = session.createConsumer(queue);
            while(true) {
                //设置接收者接收消息的时间，为了便于测试，这里定为100s
                Message message = consumer.receive(100000);
                if (message != null) {
                    System.out.println(message);
                } else {
                    //超时结束
                    break;
                }
            }
            consumer.close();
            session.close();
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
